package com.jeesite.modules.receipt.service;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeesite.common.entity.Page;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.receipt.entity.ReceiptHeader;
import com.jeesite.modules.receipt.dao.ReceiptHeaderDao;
import com.jeesite.modules.receipt.entity.ReceiptLines;
import com.jeesite.modules.receipt.dao.ReceiptLinesDao;

/**
 * 收料单Service
 * @author 码脑洞
 * @version 2025-04-13
 */
@Service
public class ReceiptHeaderService extends CrudService<ReceiptHeaderDao, ReceiptHeader> {
	
	@Autowired
	private ReceiptLinesDao receiptLinesDao;
	
	/**
	 * 获取单条数据
	 * @param receiptHeader
	 * @return
	 */
	@Override
	public ReceiptHeader get(ReceiptHeader receiptHeader) {
		ReceiptHeader entity = super.get(receiptHeader);
		if (entity != null){
			ReceiptLines receiptLines = new ReceiptLines(entity);
			receiptLines.setStatus(ReceiptLines.STATUS_NORMAL);
			entity.setLinesList(receiptLinesDao.findList(receiptLines));
		}
		return entity;
	}
	
	/**
	 * 查询分页数据
	 * @param receiptHeader 查询条件
	 * @param receiptHeader page 分页对象
	 * @return
	 */
	@Override
	public Page<ReceiptHeader> findPage(ReceiptHeader receiptHeader) {
		return super.findPage(receiptHeader);
	}
	
	/**
	 * 查询列表数据
	 * @param receiptHeader
	 * @return
	 */
	@Override
	public List<ReceiptHeader> findList(ReceiptHeader receiptHeader) {
		return super.findList(receiptHeader);
	}
	
	/**
	 * 查询子表分页数据
	 * @param receiptLines
	 * @param receiptLines page 分页对象
	 * @return
	 */
	public Page<ReceiptLines> findSubPage(ReceiptLines receiptLines) {
		Page<ReceiptLines> page = receiptLines.getPage();
		page.setList(receiptLinesDao.findList(receiptLines));
		return page;
	}
	
	/**
	 * 保存数据（插入或更新）
	 * @param receiptHeader
	 */
	@Override
	@Transactional
	public void save(ReceiptHeader receiptHeader) {
		super.save(receiptHeader);
		// 保存 ReceiptHeader子表
		for (ReceiptLines receiptLines : receiptHeader.getLinesList()){
			if (!ReceiptLines.STATUS_DELETE.equals(receiptLines.getStatus())){
				receiptLines.setHeaderId(receiptHeader);
				if (receiptLines.getIsNewRecord()){
					receiptLinesDao.insert(receiptLines);
				}else{
					receiptLinesDao.update(receiptLines);
				}
			}else{
				receiptLinesDao.delete(receiptLines);
			}
		}
	}
	
	/**
	 * 更新状态
	 * @param receiptHeader
	 */
	@Override
	@Transactional
	public void updateStatus(ReceiptHeader receiptHeader) {
		super.updateStatus(receiptHeader);
	}
	
	/**
	 * 删除数据
	 * @param receiptHeader
	 */
	@Override
	@Transactional
	public void delete(ReceiptHeader receiptHeader) {
		super.delete(receiptHeader);
		ReceiptLines receiptLines = new ReceiptLines();
		receiptLines.setHeaderId(receiptHeader);
		receiptLinesDao.deleteByEntity(receiptLines);
	}
	
}